#include "sleeword.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <iostream>

using namespace std;

SleeWord::SleeWord():
    mb_word_ok(false),
    m_last_id(0)
{
}

quint32 SleeWord::gen_id()
{
    return ++m_last_id;
}

bool SleeWord::is_id_ok(quint32 id)
{
    return  mqh_docs.keys().contains(id);
}


void SleeWord::run_word()
{
    if(mb_word_ok) return;
    m_word.mp = new QAxObject ("Word.Application");
    m_documents.mp = m_word.mp->querySubObject("Documents");
    mb_word_ok = m_documents.is_ok();
}

void SleeWord::quit_word()
{
    if(!mb_word_ok) return;
    foreach(SleeWordDoc *p_doc, mqh_docs)
    {
        p_doc->close();
        delete p_doc;
    }
    m_documents.free_ptr();
    m_word.mp->dynamicCall("Quit()");
    m_word.free_ptr();
    mb_word_ok = false;
}

void SleeWord::set_visible(bool state)
{
    if(!mb_word_ok) return;
    m_word.mp->dynamicCall("SetVisible(bool)", state);
}

SleeWordDoc * SleeWord::open_document(QString file_pathname)
{
    if(!QFile::exists(file_pathname))
    {
        qCritical()<<"requested file doesn't exists";
        return NULL;
    }
    if(!mb_word_ok) run_word();
    if(!mb_word_ok) return NULL;

    quint32 id = gen_id();
    SleeQAxPtr word_doc;
    word_doc.mp = m_documents.mp->querySubObject("Open(const QString &)", file_pathname);
    if(!word_doc.is_ok())
    {
        qDebug()<<"unable to open requested document";
        return 0;
    }
    mqh_docs[id] = new SleeWordDoc(word_doc,id);
    return mqh_docs[id];
}

SleeWordDoc * SleeWord::create_new(QString template_file_pathname)
{
    if(!template_file_pathname.isEmpty())
    {
        if(!QFile::exists(template_file_pathname))
        {
            qCritical()<<"requested template file doesn't exists";
            return NULL;
        }
    }
    if(!mb_word_ok) run_word();
    if(!mb_word_ok) return NULL;

    quint32 id = gen_id();
    SleeQAxPtr word_doc;
    if(template_file_pathname.isEmpty())
    {
        word_doc.mp = m_documents.mp->querySubObject("Add()");
    }
    else
    {
        word_doc.mp = m_documents.mp->querySubObject("Add(QVariant )", QVariant(template_file_pathname));
    }

    if(!word_doc.is_ok())
    {
        qDebug()<<"unable to open requested document";
        return 0;
    }
    mqh_docs[id] = new SleeWordDoc(word_doc,id);
    return mqh_docs[id];
}

void SleeWord::close_document(SleeWordDoc **pp_doc)
{
    if((*pp_doc) == NULL) return;
    quint32 id = (*pp_doc)->get_id();
    if(!is_id_ok(id)) return;
    (*pp_doc)->close();
    delete (*pp_doc);
    mqh_docs.remove(id);
    (*pp_doc) = NULL;
}

QString SleeWord::generate_documentation(const QDir &dir)
{
//    QFile out_file;
//    QString filename;
//    QTextStream out;
    QString ret_val;

//    QAxObject *p_word = new QAxObject("Word.Application");
//    p_word->dynamicCall("SetVisible(bool )", true);
//    filename = dir.path() + "/00_word.html";
//    out_file.setFileName(filename);
//    out_file.open(QIODevice::WriteOnly);
//    out.setDevice(&out_file);
//    out<<p_word->generateDocumentation();
//    out_file.close();



//    QAxObject *p_documents = p_word->querySubObject("Documents()");
//    filename = dir.path() + "/01_documents.html";
//    out_file.setFileName(filename);
//    out_file.open(QIODevice::WriteOnly);
//    out.setDevice(&out_file);
//    out<<p_documents->generateDocumentation();
//    out_file.close();

//    QAxObject *p_doc = p_documents->querySubObject("Add(QVariant )", QVariant("w:\\SleeOffice\\test.dot"));
////    QAxObject *p_doc = p_documents->querySubObject("Add( )");

//    filename = dir.path() + "/02_document.html";
//    out_file.setFileName(filename);
//    out_file.open(QIODevice::WriteOnly);
//    out.setDevice(&out_file);
//    out<<p_doc->generateDocumentation();
//    out_file.close();

//    QAxObject *p_selection = p_word->querySubObject("Selection()");
//    filename = dir.path() + "/01_00_selection.html";
//    out_file.setFileName(filename);
//    out_file.open(QIODevice::WriteOnly);
//    out.setDevice(&out_file);
//    out<<p_selection->generateDocumentation();
//    out_file.close();

//        QAxObject *p_range = p_doc->querySubObject("Range()");
//        filename = dir.path() + "/03_range.html";
//        out_file.setFileName(filename);
//        out_file.open(QIODevice::WriteOnly);
//        out.setDevice(&out_file);
//        out<<p_range->generateDocumentation();
//        out_file.close();

//    QAxObject *p_find = p_range->querySubObject("Find()");
//    filename = dir.path() + "/01_00_00_find.html";
//    out_file.setFileName(filename);
//    out_file.open(QIODevice::WriteOnly);
//    out.setDevice(&out_file);
//    out<<p_find->generateDocumentation();
//    out_file.close();
////(QVariant& FindText = 0,
//// QVariant& MatchCase = 0,
//// QVariant& MatchWholeWord = 0,
//// QVariant& MatchWildcards = 0,
//// QVariant& MatchSoundsLike = 0,
//// QVariant& MatchAllWordForms = 0,
//// QVariant& Forward = 0,
//// QVariant& Wrap = 0,
//// QVariant& Format = 0,
// // QVariant& ReplaceWith = 0
//    QList<QVariant> qv_arg_list;
//    QString qstr_name = QString::fromUtf8("Пупкин Василий Алибабаевич");
//    qv_arg_list<< QVariant("$FIO")<<QVariant()<<QVariant()<<QVariant()<<QVariant()<<QVariant()<<QVariant(true)<<QVariant()<<QVariant()<<QVariant(qstr_name);
//    bool b_res = true;
//    while(b_res)
//    {
//        QAxObject *p_all_range = p_doc->querySubObject("Range()");
//        QAxObject *p_temp_find = p_all_range->querySubObject("Find()");
//        b_res = p_temp_find->dynamicCall("Execute(QVariant, QVariant, QVariant, QVariant, QVariant, QVariant, QVariant, QVariant, QVariant, QVariant)",
//                        qv_arg_list).toBool();

//        delete p_temp_find;
//        delete p_all_range;
//    }
////                        QVariant("field"),
////                        QVariant(),QVariant(),QVariant(),QVariant(),
////                        QVariant(true),
////                        QVariant(),QVariant(),
////                        QVariant("new text set"));
//    ret_val.sprintf("find result: %d", b_res);




//    QAxObject *p_replacement = p_find->querySubObject("Replacement()");
//    filename = dir.path() + "/01_00_00_00replacement.html";
//    out_file.setFileName(filename);
//    out_file.open(QIODevice::WriteOnly);
//    out.setDevice(&out_file);
//    out<<p_replacement->generateDocumentation();
//    out_file.close();

//     p_replacement->dynamicCall("SetText(QString)", "new set");

////    QAxObject *p_fields = p_doc->querySubObject("Fields()");
////    filename = dir.path() + "/01_01_fields.html";
////    out_file.setFileName(filename);
////    out_file.open(QIODevice::WriteOnly);
////    out.setDevice(&out_file);
////    out<<p_fields->generateDocumentation();
////    out_file.close();

////    ret_val.sprintf("Fields count %d", p_fields->property("Count").toInt());

////    QAxObject *p_field = p_fields->querySubObject("Item(int)", 1);
////    filename = dir.path() + "/01_02_field.html";
////    out_file.setFileName(filename);
////    out_file.open(QIODevice::WriteOnly);
////    out.setDevice(&out_file);
////    out<<p_field->generateDocumentation();
////    out_file.close();


////    QAxObject *p_code = p_field->querySubObject("Code()");
////    filename = dir.path() + "/01_03_code.html";
////    out_file.setFileName(filename);
////    out_file.open(QIODevice::WriteOnly);
////    out.setDevice(&out_file);
////    out<<p_code->generateDocumentation();
////    out_file.close();



////    QAxObject *p_words = p_doc->querySubObject("Words()");
////    filename = dir.path() + "/04_words.html";
////    out_file.setFileName(filename);
////    out_file.open(QIODevice::WriteOnly);
////    out.setDevice(&out_file);
////    out<<p_words->generateDocumentation();
////    out_file.close();

////    QAxObject *p_word_item = p_words->querySubObject("Item(int )", 1);
////    filename = dir.path() + "/05_word_item.html";
////    out_file.setFileName(filename);
////    out_file.open(QIODevice::WriteOnly);
////    out.setDevice(&out_file);
////    out<<p_word_item->generateDocumentation();
////    out_file.close();


//   // p_word->dynamicCall("Quit()");
//    delete p_doc;
//    delete p_documents;
//    delete p_selection;
//    delete p_word;
    return ret_val;
}
